package org.wisdom.data.jpa.support.events;

import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.PreInsertEvent;
import org.hibernate.event.spi.PreInsertEventListener;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.stereotype.Component;
import org.wisdom.context.WisdomContextHolder;
import org.wisdom.data.jpa.entity.WisdomEntity;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;

/**
 * 添加时间戳
 *
 * @author 张智研
 * @date 2022/05/22 14:15
 */
@Component
public class WisdomPreInsertEvent implements PreInsertEventListener {

    private final transient EntityManagerFactory entityManagerFactory;

    public WisdomPreInsertEvent(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    @PostConstruct
    private void init() {
        SessionFactoryImpl sessionFactory = entityManagerFactory.unwrap(SessionFactoryImpl.class);
        EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.PRE_INSERT).appendListener(this);
    }

    @Override
    public boolean onPreInsert(PreInsertEvent preInsertEvent) {
        if (preInsertEvent.getEntity() instanceof WisdomEntity) {
            String[] names = preInsertEvent.getPersister().getPropertyNames();
            for (int i = 0; i < names.length; i++) {
                if ("timeStamp".equals(names[i])) {
                    preInsertEvent.getState()[i] = System.currentTimeMillis();
                } else if ("tenantId".equals(names[i])) {
                    preInsertEvent.getState()[i] = WisdomContextHolder.getContext().getTenantId();
                } else if ("createDeptId".equals(names[i])) {
                    preInsertEvent.getState()[i] = WisdomContextHolder.getContext().getDeptId();
                }  else if ("createDeptIdPath".equals(names[i])) {
                    preInsertEvent.getState()[i] = WisdomContextHolder.getContext().getDeptPath();
                } else if ("createCompanyId".equals(names[i])) {
                    preInsertEvent.getState()[i] = WisdomContextHolder.getContext().getCompanyId();
                }
            }
        }
        return false;
    }
}
